<script setup>

import {onMounted, ref} from "vue"
import {ElMessage} from "element-plus"
 import {userRegisterService,userLoginService,captchaService} from "@/api/user"
//引入路由
import {useRouter} from 'vue-router'
const router = useRouter()
// //引入tokenStore
import {useTokenStore} from "@/stores/token.js"
const tokenStore = useTokenStore()
const isRegister = ref(false)
//验证码图片
const captchaUrl= ref()
//注册
//定义注册数据模型
const registerData = ref({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  code:'',
})
//校验再次输入密码的函数
const checkRePassword = (rule,value,callback)=>{
  if(value === ''){
    callback(new Error("请再次输入密码"))
  }else if(registerData.value.userPassword !== value)
  {
     callback(new Error("两次密码不一致"))
  }else{
     callback()
  }
}
//定义注册表单校验规则
const rules ={
  userAccount:[
    {required:true,message:"请输入账号",trgger:"blur"},
    {min:4,max:16,message:"长度为4-16位非空字符",trgger:"blur"}
  ],
  userPassword:[
  {required:true,message:"请输入密码",trgger:"blur"},
  {min:8,max:16,message:"长度为8-16位非空字符",trgger:"blur"}
  ],
  checkPassword:[{validator:checkRePassword,trgger:"blur"}],
  code:[ {required:true,message:"请输入验证码",trgger:"blur"},]
}
//调用后台接口完成注册
const register = async()=>{
  let result = await userRegisterService(registerData.value);
  ElMessage({
      showClose: true,
      message: result.description?result.description:"注册成功",
      type: 'success',
    })
    clearRegisterData()
    isRegister.value = false
}
//登录
//绑定数据，复用注册表单数据模型
//复用注册表单校验规则
const login=async()=>{
  let result = await userLoginService(registerData.value)
  if(result.code===0){
    ElMessage({
      showClose: true,
      message: result.description?result.description:"登录成功",
      type: 'success',
    })
    tokenStore.setToken(result.data)
    // 跳转到首页
    router.push('/')
  }
  getCaptcha();
 
}

  //获取验证码
  const getCaptcha = async()=>{
  let result = await captchaService() 
  captchaUrl.value = result.data
  
}
onMounted(()=>{
// 在这里调用getCaptcha函数,不调用钩子函数不生效
getCaptcha();

})
//更新验证码
const refreshCaptcha = async()=>{
  let result = await captchaService() 
  captchaUrl.value = result.data
}


//刷新验证码

//定义函数，清空数据模型
const clearRegisterData = ()=>{
  registerData.value = {
    userAccount: '',
    userPassword: '',
    checkPassword: '',
    code: '',
  }
}
</script>
<template>
  <el-row class="login-page">
    <el-col :span="12" class="bg"></el-col>
    <el-col :span="6" :offset="3" class="form">
      <!-- 注册表单 -->
      <el-form ref="form" size="large" autocomplete="on" v-if="isRegister" :model="registerData" :rules="rules">
        <el-form-item>
          <h1>注册</h1>
        </el-form-item>
        <el-form-item prop="userAccount">
          <el-input :prefix-icon="User" placeholder="请输入账号" v-model="registerData.userAccount"/>
        </el-form-item>
        <el-form-item prop="userPassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.userPassword" show-password/>
        </el-form-item>
        <el-form-item prop="checkPassword">
          <el-input :prefix-icon="Lock" type="password" placeholder="请输入再次密码" v-model="registerData.checkPassword" show-password/>
        </el-form-item>
        <!-- 注册按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="register" :disabled="registerData.userAccount==='' || registerData.userPassword===''|| registerData.checkPassword===''">
            注册
          </el-button>

        </el-form-item>
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = false;clearRegisterData()">
            ← 返回
          </el-link>
        </el-form-item>
      </el-form>

      <!-- 登录表单 -->
      <el-form ref="form" size="large" autocomplete="off" v-else :model="registerData" :rules="rules">
        <el-form-item>
          <h1>登录</h1>
        </el-form-item>
        <el-form-item prop="userAccount">
          <el-input :prefix-icon="User" placeholder="请输入账号" v-model="registerData.userAccount"></el-input>
        </el-form-item>
        <el-form-item prop="userPassword">
          <el-input name="password" :prefix-icon="Lock" type="password" placeholder="请输入密码" v-model="registerData.userPassword" show-password/>
        </el-form-item>
        <el-form-item prop="code">
          <el-input  :prefix-icon="Lock" type="text" placeholder="点击图片更换验证码" v-model="registerData.code"  style="width: 230px;margin-right: 5px;"/>
          <img :src="captchaUrl" @click="refreshCaptcha">
        </el-form-item>
        <el-form-item class="flex">
          <div class="flex">
            <el-checkbox>记住我</el-checkbox>
            <el-link type="primary" :underline="false">忘记密码？</el-link>
          </div>
        </el-form-item>
        <!-- 登录按钮 -->
        <el-form-item>
          <el-button class="button" type="primary" auto-insert-space @click="login" :disabled="registerData.userAccount==='' || registerData.userPassword===''" >
            登录
          </el-button>
        </el-form-item>
  
        <el-form-item class="flex">
          <el-link type="info" :underline="false" @click="isRegister = true;clearRegisterData()" >
            注册 →
          </el-link>
        </el-form-item>
      </el-form>
    </el-col>
  </el-row>
</template>

<style lang="scss" scoped>
/* 样式 */
.login-page {
  height: 100vh;
  background-color: #fff;

  .bg {
    background: url('@/assets/logo2.png') no-repeat 60% center / 240px auto,
    url('@/assets/login_bg.jpg') no-repeat center / cover;
    border-radius: 0 20px 20px 0;
  }

  .form {
    display: flex;
    flex-direction: column;
    justify-content: center;
    user-select: none;

    .title {
      margin: 0 auto;
    }

    .button {
      width: 100%;
    }

    .flex {
      width: 100%;
      display: flex;
      justify-content: space-between;
    }
  }
}
</style>